//
//  HJRefreshControl.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/24.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
let HJRefreshControlH:CGFloat = 50
enum HJRefreshControlState:Int {
    case Nomal = 0
    case Pulling = 1
    case Refreshing = 2
}
class HJRefreshControl: UIControl {
    
    var hjState:HJRefreshControlState = .Nomal{
        didSet{
            switch hjState {
            case .Pulling:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "释放刷新"
            case .Refreshing:
                self.arrowImage.hidden = true
                self.indecatorView.startAnimating()
                self.messageLabel.text = "正在刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + HJRefreshControlH
                })
                //调用刷新方法
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            case .Nomal:
                self.indecatorView.stopAnimating()
                self.arrowImage.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - HJRefreshControlH
                    })
                }
            }
        }
        
    }
        
    func endRefreshing(){
        hjState = .Nomal
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI(){
//        backgroundColor = UIColor.orangeColor()
        self.frame.size.height = HJRefreshControlH
//        self.frame.size.width = ScreenWidth
        self.frame.origin.y = -HJRefreshControlH
        
        //添加控件
        addSubview(arrowImage)
        addSubview(messageLabel)
        addSubview(indecatorView)
        
        //约束控件
        arrowImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.leading.equalTo(arrowImage.snp_trailing)
        }
        indecatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImage)
        }
    }
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
            return
        }
        self.tableView = tableView as? UIScrollView
        self.frame.size.width  = tableView.frame.size.width
        //1> 添加KVO观察者
        tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    //2> 实现KVO观察方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let contentOffset = self.tableView?.contentOffset
//        print(contentOffset?.y)
        let conditionValue = -(self.tableView!.contentInset.top + HJRefreshControlH)//负数
        if tableView!.dragging {//手指拖拽还没有放开
            if contentOffset?.y < conditionValue && hjState == .Nomal{//
                print("完全显示")
                hjState = .Pulling
            }else{
                if contentOffset?.y >= conditionValue && hjState == .Pulling{
                    print("下拉刷新")
                    hjState = .Nomal
                }
            }
        }else{//松开手指
            if hjState == .Pulling {//完全显示出来
                print("刷新中...")
                hjState = .Refreshing
            }
        }
    }
    //3> 移除观察着
    deinit{
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    private weak var tableView:UIScrollView?
    //懒加载控件
    private var arrowImage:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        
        label.text = "下拉刷新"
        return label
    }()
    private var indecatorView:UIActivityIndicatorView = {
    
        let indecator = UIActivityIndicatorView()
        indecator.color = UIColor.darkGrayColor()
        return indecator
    
    }()
}
